package com.promise.jokerdream.ui.settings

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.promise.jokerdream.database.entity.KnightArenaGameConfigEntity
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.response.pc.QueryKnightArenaListResponse
import com.promise.jokerdream.model.knight.KnightAreanKnightModel
import com.promise.jokerdream.ui.components.MultiSelectHashtagBottomSheet
import com.promise.jokerdream.ui.components.RoundCheckbox
import com.promise.jokerdream.ui.components.SelectionRow
import com.promise.jokerdream.ui.components.SettingCard
import com.promise.jokerdream.ui.components.TimePickerDialog
import androidx.compose.foundation.border
import androidx.compose.foundation.background
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.sp
import androidx.compose.foundation.shape.RoundedCornerShape
import com.promise.jokerdream.config.game.KnightArenaFormation
import com.promise.jokerdream.ui.components.CheckboxOptionRow
import com.promise.jokerdream.ui.theme.AppFontSizes
import com.promise.jokerdream.ui.theme.AppSpacing
import kotlinx.serialization.json.Json

@Composable
fun KnightArenaSettingCard(
    config: KnightArenaGameConfigEntity,
    onEnabledChange: (Boolean) -> Unit,
    onScheduledChallengeChange: (Boolean) -> Unit,
    onRegistrationTimeChange: (String) -> Unit,
    onFormationsChange: (List<KnightArenaFormation>) -> Unit,
    modifier: Modifier = Modifier,
    onExecuteClick: (() -> Unit)? = null
) {
    SettingCard(
        title = "侠士论剑",
        description = "",
        checked = config.enabledSetting,
        onCheckedChange = onEnabledChange,
        modifier = modifier,
        onExecuteClick = onExecuteClick,
        content = {
            if (config.enabledSetting) {
                Column(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    // 确保始终渲染两个阵容项
                    val formations = remember(config.formationsJson) {
                        val base = try {
                            if (config.formationsJson.isEmpty()) {
                                emptyList()
                            } else {
                                Json.decodeFromString<List<KnightArenaFormation>>(config.formationsJson)
                            }
                        } catch (e: Exception) {
                            emptyList()
                        }
                        when (base.size) {
                            0 -> listOf(
                                KnightArenaFormation(name = "阵容1"),
                                KnightArenaFormation(name = "阵容2")
                            )
                            1 -> listOf(
                                base[0],
                                KnightArenaFormation(name = "阵容2")
                            )
                            else -> base
                        }
                    }

                    // 渲染两个阵容
                    FormationItem(
                        index = 0,
                        formation = formations[0],
                        onEditFormation = { updated ->
                            val newList = formations.toMutableList()
                            newList[0] = updated
                            // 通过 onFormationsChange 更新 JSON 字符串
                            onFormationsChange(newList)
                        }
                    )
                    Spacer(modifier = Modifier.height(AppSpacing.componentSmall))
                    FormationItem(
                        index = 1,
                        formation = formations[1],
                        onEditFormation = { updated ->
                            val newList = formations.toMutableList()
                            // 若原有 formations 少于2，需要补齐第0项
                            if (newList.size == 1) {
                                newList.add(updated)
                            } else {
                                newList[1] = updated
                            }
                            onFormationsChange(newList)
                        }
                    )

                    Spacer(modifier = Modifier.height(AppSpacing.componentMedium))

                    // 定时挑战
                    CheckboxOptionRow(
                        title = "定时挑战",
                        checked = config.scheduledChallengeEnabled,
                        onCheckedChange = onScheduledChallengeChange
                    )

                    if (config.scheduledChallengeEnabled) {
                        ChallengeTimeSelector(
                            selectedTime = config.registrationTime,
                            onTimeChange = onRegistrationTimeChange
                        )
                    }
                }
            }
        }
    )

    // 由 FormationItem 控制各自的 bottom sheet
}

@Composable
private fun ChallengeTimeSelector(
    selectedTime: String,
    onTimeChange: (String) -> Unit
) {
    var showTimePicker by remember { mutableStateOf(false) }
    SelectionRow(
        label = "挑战时间：",
        selectedText = selectedTime,
        onClick = { showTimePicker = true }
    )
    TimePickerDialog(
        show = showTimePicker,
        onTimeSelected = { time ->
            onTimeChange(time)
            showTimePicker = false
        },
        onDismiss = { showTimePicker = false },
        selectedTime = selectedTime
    )
}

@Composable
private fun FormationItem(
    index: Int,
    formation: KnightArenaFormation,
    onEditFormation: (KnightArenaFormation) -> Unit
) {
    var showBottomSheet by remember { mutableStateOf(false) }

    // 阵容选择行
    val names = remember(formation.knights) { formation.knights.map { it.name }.filter { it.isNotBlank() } }
    val joinedNames = remember(names) { if (names.isEmpty()) "未选择" else names.joinToString(separator = "、") }
    SelectionRow(
        label = "阵容${index + 1}：",
        selectedText = joinedNames,
        onClick = { showBottomSheet = true }
    )

    Spacer(modifier = Modifier.height(AppSpacing.componentSmall))
    ChallengeCountItem(
        index = index,
        value = formation.challengeCount,
        onValueChange = { count ->
            onEditFormation(formation.copy(challengeCount = count))
        }
    )

    if (showBottomSheet) {
        val gameApi = remember { GameApi.getInstance() }
        var recommended by remember { mutableStateOf<List<KnightAreanKnightModel>>(emptyList()) }
        var loaded by remember { mutableStateOf(false) }

        LaunchedEffect(Unit) {
            gameApi.queryKnightArenaList().fold(
                onSuccess = { resp: QueryKnightArenaListResponse ->
                    recommended = resp.knights
                    loaded = true
                },
                onFailure = {
                    loaded = true
                }
            )
        }

        val initialNames = formation.knights.map { it.name }
        var selectedNames by remember(formation) { mutableStateOf(initialNames) }
        MultiSelectHashtagBottomSheet(
            title = "选择阵容",
            initialTags = selectedNames,
            placeholder = "输入侠士名，回车添加",
            recommendedTags = if (loaded) recommended.map { it.name } else emptyList(),
            onCancel = { showBottomSheet = false },
            onComplete = { names ->
                selectedNames = names
                val mapped = names.mapNotNull { name ->
                    recommended.firstOrNull { it.name == name }
                }
                onEditFormation(formation.copy(knights = mapped))
                showBottomSheet = false
            },
            onDismiss = { showBottomSheet = false }
        )
    }
}

@Composable
private fun ChallengeCountItem(
    index: Int,
    value: Int,
    onValueChange: (Int) -> Unit,
    modifier: Modifier = Modifier
) {
    Row(
        modifier = modifier,
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        // “挑战前” 文案
        Text(
            text = "挑战${if (index == 0) "前" else "后"}",
            fontSize = AppFontSizes.mediumBody,
            color = MaterialTheme.colorScheme.onSurface
        )
        Box(
            modifier = Modifier
                .width(72.dp)
                .height(24.dp)
                .background(
                    color = MaterialTheme.colorScheme.surface,
                    shape = RoundedCornerShape(6.dp)
                )
                .border(
                    width = 1.dp,
                    color = MaterialTheme.colorScheme.outline,
                    shape = RoundedCornerShape(6.dp)
                )
                .padding(horizontal = 6.dp),
            contentAlignment = Alignment.Center
        ) {
            var text by remember(value) { mutableStateOf(value.coerceIn(1, 99).toString()) }
            BasicTextField(
                value = text,
                onValueChange = { newValue ->
                    if (newValue.all { it.isDigit() } && newValue.length <= 2) {
                        text = newValue
                        val parsed = newValue.toIntOrNull()
                        if (parsed != null) {
                            onValueChange(parsed.coerceIn(1, 99))
                        }
                    } else if (newValue.isEmpty()) {
                        text = ""
                    }
                },
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                singleLine = true,
                textStyle = androidx.compose.ui.text.TextStyle(
                    fontSize = 13.sp,
                    color = MaterialTheme.colorScheme.onSurface,
                    textAlign = TextAlign.Center
                ),
                decorationBox = { inner -> inner() }
            )
        }
        // “次” 文案
        Text(
            text = "次",
            fontSize = AppFontSizes.mediumBody,
            color = MaterialTheme.colorScheme.onSurface
        )
    }
}


